package reseauSocial;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import main.SYRRES;
import core.Beer;
import core.SetBeer;
import core.SetUser;
import core.User;

public class PredictNote {
	
	private SetBeer allBeer;
	private SetUser allUser;
	
	private int threshold;
	
	public PredictNote(SetBeer allBeer, SetUser allUser) {
		this.allBeer = allBeer;
		this.allUser = allUser;
	}
	
	public void predict(int threshold) {
		this.threshold = threshold;
		
		calculBeerRelation(threshold);
		searchNprediteNotes();
	}
	
	public void calculBeerRelation(int threshold) {
		int weight;
		Beer b1;
		Beer b2;
		
		for (int i = 0; i < allBeer.size(); i++) {
			for (int j = i + 1; j < allBeer.size(); j++) {
				if (i != j) {
					b1 = allBeer.getBeer(i);
					b2 = allBeer.getBeer(j);
					weight = calculWeight(b1, b2);
					if (weight >= threshold && weight > 0) {
						b1.addBeer(b2.getId(), weight);
						b2.addBeer(b1.getId(), weight);
					}
				}
			}
		}
	}
	
	public int calculWeight(Beer b1, Beer b2) {
		int weight = 0;
		
		Set<String> b1Users = b1.getUserNote().keySet();
		Set<String> b2Users = b2.getUserNote().keySet();
		
		for (String b1User : b1Users) {
			for (String b2User : b2Users) {
				if (b1User.equals(b2User)) 		weight++;
			}
		}		
		return weight;
	}
	
	public void searchNprediteNotes() {
		Beer beer;
		User user;
		int countA = 0;
		
		for (int i = 0; i < allUser.size(); i++) {
			user = allUser.getUser(i);
			for (int j = 0; j < allBeer.size(); j++) {
				beer = allBeer.getBeer(j);
				
				if (!user.hasBeer(beer.getId())) {
					if (beer.canConnectWith(user.getBiereNote().keySet(), threshold)) {
						countA++;
						beer.addUser(user.getId(), getPredictNote(beer, user));
					} 
				} else {
					continue;
				}
			}
		}		
		System.out.println(countA);
	}
	
	public List<Integer> getPredictNote(Beer beer, User user) {
		List<Integer> notes = new ArrayList<Integer>();
		for (int i = 0; i < SYRRES.NB_NOTE; i++) {
			notes.add(normalize(user.getAverageNote(i) + beer.getAverageNote(i) - SYRRES.getAverageNote(i)));
		}
		return notes;
	}
	
	public int normalize(double note) {
		if (note >= 0.5) {
			return 1;
		} else if (note <= -0.5) {
			return -1;
		} else {
			return 0;
		}
	}
}